define(['./../model/ProjectMap'], function () {
    'use strict';
    var app = angular.module('App');
    app.factory('loadProjectMap', ['ProjectMap', '$q', 'symbolFactory', '$timeout', '$rootScope', 'viewbag',
        function (ProjectMap, $q, symbolFactory, $timeout, $rootScope, viewbag) {
            var map = null;
            var curPoints = null; //当前选中的location点集
            var prj = null;
            /** 当地图缩放的时候添加remark点的text标记 */
            var addPointsTxt = function (currentZoom) {
                if (!curPoints) return;
                var mlayer = map.curPointTxtLayer;
                //这是一个缩放判断,如果满足这个条件,说明文字能很好的嵌入marker间
                var txtXoffset = map.unproject([0, 20], currentZoom).lat;
                if (Math.abs(txtXoffset) > 5) return;
                curPoints.forEach(function (pt) {
                    var labelIcon = L.divIcon({
                        'html': '<span>' + pt.name + '</span>',
                        'className': 'point-marker-txt',
                        'iconSize': L.point(100, 10)
                    });
                    var marker = L.marker([pt.geometry[1] - txtXoffset, pt.geometry[0] - txtXoffset], {
                        icon: labelIcon
                    });
                    if (!pt.visible) {

                    } else {
                        mlayer.addLayer(marker);
                    }
                });
            };
            /** 缩放点的图例 */
            var zoomMarkers = function (preZoom, currentZoom) {
                var classZoom = currentZoom >= 3 ? 3 : currentZoom;
                var className = "map-zoom-" + classZoom.toString();
                $(".point-marker").removeClass('map-zoom-' + preZoom.toString());
                $(".point-marker").addClass(className);
            };
            /** 记载布点图的底图 */
            var loadProjectMap = function (domId) {
                prj = viewbag.curPrj;//获取当前的项目
                map && map.remove();
                var CustomZoom = L.extend({}, L.CRS.Simple, {
                    scale: function (zoom) {
                        return prj.zoomRatio * Math.pow(2, zoom);
                    }
                });
                service.map = map = new ProjectMap(domId || 'json-map', {
                    crs: CustomZoom,
                    zoom: 1,
                    zoomControl: false,
                    maxZoom: 8,
                    doubleClickZoom: false
                });
                map.attributionControl.setPrefix('');
                map.showLoadingBar();
                map.setView(prj.projectMapCenter, 1);
                map.loadProjectLayers(prj.layerList);//加载背景图层
                // renderPointsOnMap();//加载当前点
                map.addEventListener('renderPointsRequired', function (event) {
                    //当需要重新加载其他点的时候,取消自动化
                    map.toggleAutoSurvey(false); //取消自动化
                    renderPointsOnMap().then(function (targetPoints) {
                        curPoints = targetPoints;
                    });
                });

                /** 开始缩放前的尺度 */
                var startZoomLevel = 0;

                map.on('zoomend', function (event) {
                    var currentZoom = this.getZoom();
                    zoomMarkers(startZoomLevel, currentZoom);
                    addPointsTxt(currentZoom);
                });

                map.on('zoomstart', function (event) {
                    startZoomLevel = this.getZoom();
                    map.curPointTxtLayer.clearLayers();
                });
                //注册marker的hover事件
                var _curHoverPointNameOnHighchart = null;//当前highchart上hover的点号
                var _highLightPtNameList = [];

                /** 清楚高亮显示的marker */
                function clearHighLightMarker() {
                    _highLightPtNameList.forEach(function (ptName) {
                        $(document.getElementById(ptName)).parent().removeClass('point-marker-active');
                    });
                    _highLightPtNameList.length = 0;
                }

                map.addEventListener('makerHoverActive', function (event) {
                    var name = event.ptName;
                    _curHoverPointNameOnHighchart = name;//当前highchart上停留的点
                    var marker = map.curPointMarksLayer.getLayers().filter(function (marker) {
                        return marker.name === name;
                    })[0];
                    if (!marker) return;
                    var pos = marker.getLatLng();
                    var offset = map.unproject([0, 200], map.getZoom());
                    $timeout(function () {
                        if (name === _curHoverPointNameOnHighchart) { //用户鼠标停留800ms以上才打开popup
                            clearHighLightMarker();
                            map.zoomToPoint([pos.lat + offset.lat, pos.lng]).then(function () {
                                $(document.getElementById(name)).parent().addClass('point-marker-active');
                                _highLightPtNameList.push(name);
                            });
                        }
                    }, 800);

                });
                map.addEventListener('makerHoverInactive', function (event) {
                    if (map.autoSurveyMode) return;
                    var name = event.ptName;
                    _curHoverPointNameOnHighchart = null;
                    $timeout(function () {
                        $('#' + name).parent().removeClass('point-marker-active');
                    }, 100);
                });
                map.on('click', function (event) {

                });
                return map;
            };
            /** 加载当前的监测点图 */
            var renderPointsOnMap = function (lpts) {
                service.map.clearPointsLayer();
                if (!lpts) {
                    lpts = prj.findLocationPoints();
                }
                curPoints = lpts.points;
                if (!lpts.isRingNumberConfig) return;
                var first, center;
                if (curPoints.length < 4) {
                    first = curPoints[0].geometry;
                    center = L.point(first[1], first[0]);
                } else {
                    first = curPoints[3].geometry;
                    var last = curPoints[curPoints.length - 3].geometry;
                    center = L.bounds([first[1], first[0]], [last[1], last[0]]).getCenter(); //find center
                }
                var offset = map.unproject([0, 200], 1);
                map.setView([center.x + offset.lat, center.y], 1);
                curPoints.forEach(function (pt) {
                    if (!pt.geometry) {
                        console.log("点号%s的坐标在ringnumber图层中未配置", pt.name);
                        return;
                    }
                    var labelIcon = labelIconFactory(pt);
                    var marker = L.marker([pt.geometry[1], pt.geometry[0]], {
                        icon: labelIcon,
                        riseOnHover: true
                    });
                    map.curPointMarksLayer.addLayer(marker);
                    marker.name = pt.name;

                    marker.on('mouseover', function (e) {
                        // $('#' + pt.name).siblings('.ui.popup').remove();
                        $('#' + pt.name).popup({
                            position: 'top center'
                        }).popup('show');
                        setTimeout(function () {
                            $('#' + pt.name).popup('hide');
                        }, 2000);
                    });
                    marker.on('mouseout', function (e) {
                        $('#' + pt.name).popup('hide');
                    });
                    marker.on('click', function (e) {

                    });
                });

            };
            function labelIconFactory(pt) {
                var labelIcon = null;
                var ringNubmerStr = (pt.ringNumber - 0) > 0 ? (pt.ringNumber - 0) : '无';//防止ringnumber前有0,所有要换成数字
                var html = "<table class='point-popup-table'>" +
                    '<tr><td>点号</td><td>' + pt.name + '</td></tr>' +
                    '<tr><td>环号</td><td>' + ringNubmerStr + '</td></tr>' +
                    '</table>';
                if (pt.alert) { //报警点与否
                    labelIcon = L.divIcon({
                        'html': '<div id="' + pt.name + '" data-variation="inverted" data-html="' + html + '">&nbsp;</div>',
                        'className': 'point-marker point-marker-alert map-zoom-1',
                        'iconSize': L.point(20, 20)
                    });
                } else {
                    labelIcon = L.divIcon({
                        'html': '<div id="' + pt.name + '" data-variation="inverted" data-html="' + html + '">&nbsp;</div>',
                        'className': 'point-marker point-marker-normal map-zoom-1',
                        'iconSize': L.point(20, 20)
                    });
                }
                return labelIcon;
            }
            var service = {
                loadMap: loadProjectMap,
                renderPointsOnMap: renderPointsOnMap,
                map: map
            };
            return service;
        }
    ]);
});